﻿using Microsoft.AspNetCore.Http;
using MyCommon.Extensions;
using MyCommon.Helper;
using MyCommon.Https;
using Serilog;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MySerilog.Utility
{
    public class SerilogRequestUtility
    {
        public const string HttpMessageTemplate = "HTTP {RequestMethod} {RequestPath} QueryString:{QueryString} Body:{Body}  responded {StatusCode} in {Elapsed:0.0000} ms";

        private static readonly List<string> _ignoreUrl = new List<string>()
        {
            "/job"
        };

        public static LogEventLevel GetRequestLevel(HttpContext context,double _,Exception? ex)
        {
            return ex is null && context.Response.StatusCode <= 499 ? IgnoreRequest(context) : LogEventLevel.Error;
        }

        private static LogEventLevel IgnoreRequest(HttpContext context) { 
            var path = context.Request.Path.Value;
            if (path.IsNullOrEmpty())
            {
                return LogEventLevel.Information;
            }
            return _ignoreUrl.Any(i => path.StartsWith(i)) ? LogEventLevel.Verbose : LogEventLevel.Information;
        }

        public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext context) { 
            var request = context.Request;
            diagnosticContext.Set("RequestHost", request.Host);
            diagnosticContext.Set("RequestScheme", request.Scheme);
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("RequestIp", context.GetRequestIp());
            if (request.Method == HttpMethods.Get)
            {
                diagnosticContext.Set("QueryString", request.QueryString.HasValue ? request.QueryString.Value : string.Empty);
                diagnosticContext.Set("Body",string.Empty);
            }
            else
            {
                diagnosticContext.Set("QueryString", request.QueryString.HasValue ? request.QueryString.Value : string.Empty);
                diagnosticContext.Set("Body", request.ContentLength>0?request.GetRequestBody():string.Empty);
            }

            diagnosticContext.Set("ContentType",context.Response.ContentType);
            //var endPoint = context.GetEndpoint();
            //if (endPoint != null) {
            //    diagnosticContext.Set("EndpointName", endPoint.DisplayName);
            //}
        }

    }
}
